from simple import MQTTClient
from machine import Pin
import machine
import micropython
from machine import ADC
from machine import Timer
import dht
#import ssd1306
from machine import I2C
# ESP8266 ESP-12 modules have blue, active-low LED on GPIO2, replace
# with something else if needed.
dh = dht.DHT11(machine.Pin(16))
led = Pin(12, Pin.OUT, value=1)
netTim = Timer(-1)
adc0=ADC(0)  
# MQTT服务器地址域名为：183.230.40.39,不变
SERVER = "183.230.40.39"

#设备ID
CLIENT_ID = "30974317"
#随便起个名字
TOPIC = b"m1"
#产品ID
username='137168'
#产品APIKey:
password='LfkoND=p7zLFPgx=NB2TWw94JWI='
state = 0
c = MQTTClient(CLIENT_ID, SERVER,6002,username,password)
def isPin( pin = '-1'):
        if int(pin) in (0,1,2,3,4,5,12,13,14,15,16):
            return int(pin)
        else:
            return -1
def sub_cb(topic, msg):
    global state
    print((topic, msg))
    # #################
    cmd = msg.decode('ascii').split(" ")
    print(cmd)
    if len(cmd) == 3:
            if cmd[0] == 'pin' and isPin(cmd[1]) >= 0:
                value = Pin(int(cmd[1])).value()
                if cmd[2] == 'on':
                    value = 0
                elif cmd[2] == 'off':
                    value = 1
                elif cmd[2] == 'toggle':
                    value = 1 if value == 0 else 0
                
                pin = Pin(int(cmd[1]), Pin.OUT) #, value=(1 if cmd[2] == 'on' else 0))
                pin.value(value)
            else:
                print('Pin number outof range.')
    
def sendmessage(netTim):
    
    #res=getData(1)
    
    dh.measure()
    temp=dh.temperature() # eg. 23 
    hum=dh.humidity()    # eg. 41 (% RH)
    data1={"Temp": 22.5, "GuangZhao": 95.2,"Humidity":78}
    #更改字典值
    #global lcd
    #lcd.fill(0)
    #lcd.text("GreenHouse1",20,0) 
    #lcd.text("Temp:"+str(temp),0,20) 
    #lcd.text("Humidity:"+str(hum),0,30) 
    #lcd.text("Fan: OFF",0,50)  
    #lcd.show()
    data1["GuangZhao"]=adc0.read()*0.1
    data1["Temp"]=temp
    data1["Humidity"]=hum
    
    d2=str(data1)
    d2=d2.replace("\'","\"")                            #str函数将字典转化为字符串之后“”变为‘’，需要替换回去
    str1=len(d2)
    mes1=bytes([0x03])+bytes([0x00])+bytes([str1])+d2.encode('utf-8')
    print (mes1)
    try:
      
      c.publish('$dp',mes1)
    except BaseException as e1:
      
      print("publish error")
              
def main():
    
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC))
    netTim.init(period=2000, mode=Timer.PERIODIC, callback=sendmessage)
    try:
            while 1:
                    #micropython.mem_info()
                    #c.wait_msg()
                    c.check_msg()
    finally:
            c.disconnect()

main()





